package com.example.service.impl;

import com.example.entity.CreditBehavior;
import com.example.repository.CreditBehaviorRepository;
import com.example.service.CreditBehaviorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Optional;

/**
 * 信贷行为Service实现类
 */
@Slf4j
@Service
public class CreditBehaviorServiceImpl implements CreditBehaviorService {

    @Autowired
    private CreditBehaviorRepository creditBehaviorRepository;

    @Override
    public double calculateCreditCardUtilizationRate(Long userId) {
        // 获取用户最新的信贷行为数据
        Optional<CreditBehavior> creditBehaviorOpt = creditBehaviorRepository.findLatestByUserId(userId);

        if (creditBehaviorOpt.isEmpty()) {
            log.warn("用户[{}]没有信贷行为数据", userId);
            return 0.0;
        }

        CreditBehavior creditBehavior = creditBehaviorOpt.get();

        // 计算信用卡使用率 = 已使用额度 / 授信总额
        if (creditBehavior.getTotalCreditLine() == null ||
            creditBehavior.getTotalCreditLine().compareTo(BigDecimal.ZERO) <= 0) {
            log.warn("用户[{}]授信总额为零或负值", userId);
            return 0.0;
        }

        BigDecimal usedCreditLine = creditBehavior.getUsedCreditLine() == null ?
                BigDecimal.ZERO : creditBehavior.getUsedCreditLine();

        BigDecimal utilizationRate = usedCreditLine.divide(
                creditBehavior.getTotalCreditLine(), 4, RoundingMode.HALF_UP);

        // 更新信用卡使用率
        creditBehavior.setCreditCardUtilizationRate(utilizationRate);
        creditBehaviorRepository.save(creditBehavior);

        return utilizationRate.doubleValue();
    }

    @Override
    public int getComprehensiveCreditScore(Long userId) {
        // 获取用户最新的信贷行为数据
        Optional<CreditBehavior> creditBehaviorOpt = creditBehaviorRepository.findLatestByUserId(userId);

        if (creditBehaviorOpt.isEmpty()) {
            log.warn("用户[{}]没有信贷行为数据", userId);
            return 0;
        }

        CreditBehavior creditBehavior = creditBehaviorOpt.get();

        // 综合评分计算逻辑
        // 1. 央行征信评分权重50%
        // 2. 百行征信评分权重30%
        // 3. 芝麻信用分权重20%
        int pbocScore = creditBehavior.getPbocCreditScore() == null ? 0 : creditBehavior.getPbocCreditScore();
        int baihangScore = creditBehavior.getBaihangCreditScore() == null ? 0 : creditBehavior.getBaihangCreditScore();
        int sesameScore = creditBehavior.getSesameScore() == null ? 0 : creditBehavior.getSesameScore();

        // 归一化处理（假设央行和百行评分满分1000，芝麻分满分950）
        double normalizedPboc = pbocScore / 1000.0;
        double normalizedBaihang = baihangScore / 1000.0;
        double normalizedSesame = sesameScore / 950.0;

        // 加权计算
        double weightedScore = normalizedPboc * 0.5 + normalizedBaihang * 0.3 + normalizedSesame * 0.2;

        // 转换为0-100的分数
        int comprehensiveScore = (int) Math.round(weightedScore * 100);

        return comprehensiveScore;
    }

    @Override
    public int analyzeOverdueRisk(Long userId) {
        // 获取用户最新的信贷行为数据
        Optional<CreditBehavior> creditBehaviorOpt = creditBehaviorRepository.findLatestByUserId(userId);

        if (creditBehaviorOpt.isEmpty()) {
            log.warn("用户[{}]没有信贷行为数据", userId);
            return 2; // 默认高风险
        }

        CreditBehavior creditBehavior = creditBehaviorOpt.get();

        // 获取逾期相关指标
        int historicalOverdueCount = creditBehavior.getHistoricalOverdueCount() == null ?
                0 : creditBehavior.getHistoricalOverdueCount();

        int m1OverdueCount = creditBehavior.getM1OverdueCount() == null ?
                0 : creditBehavior.getM1OverdueCount();

        int m2OverdueCount = creditBehavior.getM2OverdueCount() == null ?
                0 : creditBehavior.getM2OverdueCount();

        int m3OverdueCount = creditBehavior.getM3OverdueCount() == null ?
                0 : creditBehavior.getM3OverdueCount();

        // 风险评估逻辑
        // 低风险: 历史逾期次数≤2且无M2/M3逾期
        // 中风险: 历史逾期次数≤5且M2逾期≤2且无M3逾期
        // 高风险: 其他情况
        if (historicalOverdueCount <= 2 && m2OverdueCount == 0 && m3OverdueCount == 0) {
            return 0; // 低风险
        } else if (historicalOverdueCount <= 5 && m2OverdueCount <= 2 && m3OverdueCount == 0) {
            return 1; // 中风险
        } else {
            return 2; // 高风险
        }
    }
}